package com.huawei.demo;

import com.huawei.demo.enums.TemplateAuditState;
import com.huawei.demo.enums.TemplateState;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.core.utils.JsonUtils;
import com.huaweicloud.sdk.core.utils.StringUtils;
import com.huaweicloud.sdk.koomessage.v1.KooMessageClient;
import com.huaweicloud.sdk.koomessage.v1.model.AIMResolveTask;
import com.huaweicloud.sdk.koomessage.v1.model.AIMTemplate;
import com.huaweicloud.sdk.koomessage.v1.model.AimPersonalTemplateContent;
import com.huaweicloud.sdk.koomessage.v1.model.AimPersonalTemplateContentAction;
import com.huaweicloud.sdk.koomessage.v1.model.AimPersonalTemplateFactory;
import com.huaweicloud.sdk.koomessage.v1.model.AimPersonalTemplatePage;
import com.huaweicloud.sdk.koomessage.v1.model.CreateAimPersonalTemplateRequest;
import com.huaweicloud.sdk.koomessage.v1.model.CreateAimPersonalTemplateRequestBody;
import com.huaweicloud.sdk.koomessage.v1.model.CreateAimPersonalTemplateResponse;
import com.huaweicloud.sdk.koomessage.v1.model.CreateAimSendTaskRequest;
import com.huaweicloud.sdk.koomessage.v1.model.CreateAimSendTaskRequestBody;
import com.huaweicloud.sdk.koomessage.v1.model.CreateAimSendTaskResponse;
import com.huaweicloud.sdk.koomessage.v1.model.CreateResolveTaskParam;
import com.huaweicloud.sdk.koomessage.v1.model.ListAimSendDetailsRequest;
import com.huaweicloud.sdk.koomessage.v1.model.ListAimSendDetailsResponse;
import com.huaweicloud.sdk.koomessage.v1.model.ListAimSendTasksRequest;
import com.huaweicloud.sdk.koomessage.v1.model.ListAimSendTasksResponse;
import com.huaweicloud.sdk.koomessage.v1.model.ListAimTemplatesRequest;
import com.huaweicloud.sdk.koomessage.v1.model.ListAimTemplatesResponse;
import com.huaweicloud.sdk.koomessage.v1.model.SmsChannel;
import com.huaweicloud.sdk.koomessage.v1.model.UploadAimTemplateMaterialRequest;
import com.huaweicloud.sdk.koomessage.v1.model.UploadAimTemplateMaterialRequestBody;
import com.huaweicloud.sdk.koomessage.v1.model.UploadAimTemplateMaterialResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

public class SendAimTask {
    private static final Logger logger = LoggerFactory.getLogger(SendAimTask.class);

    public static void main(String[] args) {
        String ak = "<YOUR AK>";
        String sk = "<YOUR SK>";
        BasicCredentials credentials = new BasicCredentials().withAk(ak).withSk(sk);

        HttpConfig config = HttpConfig.getDefaultHttpConfig().withIgnoreSSLVerification(true);
        KooMessageClient kmClient = KooMessageClient.newBuilder()
            .withCredential(credentials)
            .withEndpoints(Arrays.asList("koomessage.myhuaweicloud.com"))
            .withHttpConfig(config)
            .build();

        // 上传智能信息模板素材
        UploadAimTemplateMaterialRequest uploadAimTemplateMaterialRequest = buildUploadAimTemplateMaterialRequest();
        UploadAimTemplateMaterialResponse uploadAimTemplateMaterialResponse = uploadAimTemplateMaterial(kmClient,
            uploadAimTemplateMaterialRequest);
        // 智能信息模板素材资源id
        String aimResourceId;
        if (uploadAimTemplateMaterialResponse != null && uploadAimTemplateMaterialResponse.getData() != null
            && !StringUtils.isEmpty(uploadAimTemplateMaterialResponse.getData().getAimResourceId())) {
            aimResourceId = uploadAimTemplateMaterialResponse.getData().getAimResourceId();
            System.out.println(aimResourceId);
        }

        // 创建智能信息个人模板
        CreateAimPersonalTemplateRequest createAimPersonalTemplateRequest = buildCreateAimPersonalTemplateRequest();
        CreateAimPersonalTemplateResponse createAimPersonalTemplateResponse = createAimPersonalTemplate(kmClient,
            createAimPersonalTemplateRequest);
        if (createAimPersonalTemplateResponse != null && createAimPersonalTemplateResponse.getData() != null
            && !StringUtils.isEmpty(createAimPersonalTemplateResponse.getData().getTplId())) {
            String tplId = createAimPersonalTemplateResponse.getData().getTplId();
            System.out.println(tplId);
        }

        // 您可以通过KooMessage控制台查询到以下参数
        // 智能信息模板ID,KooMessage控制台-》智能信息配置-》智能信息模板管理-》模板ID
        String tplId = "<YOUR tplId>";
        // 根据模板ID查询智能信息模板
        AIMTemplate template = getAimTemplateById(kmClient, tplId);

        // 判断模板是否审核通过并且非禁用状态
        if (template != null && TemplateAuditState.APPROVED.getCode() == template.getAuditState()
            && TemplateState.ENABLE.getCode() == template.getTplState()) {
            // 提交智能信息发送任务
            CreateAimSendTaskResponse sendTask = createSendTask(kmClient, tplId);
            // 查询发送任务提交结果
            assert sendTask != null;
            String taskId = sendTask.getTaskId();
            ListAimSendTasksRequest listAimSendTasksRequest = new ListAimSendTasksRequest();
            listAimSendTasksRequest.setOffset(0);
            listAimSendTasksRequest.setLimit(10);
            listAimSendTasksRequest.setTaskId(taskId);
            ListAimSendTasksResponse response = kmClient.listAimSendTasks(listAimSendTasksRequest);
            System.out.println(JsonUtils.toJSON(response));

            // 查询发送明细
            ListAimSendDetailsRequest listAimSendDetailsRequest = new ListAimSendDetailsRequest();
            listAimSendDetailsRequest.setOffset(0);
            listAimSendDetailsRequest.setLimit(10);
            listAimSendDetailsRequest.setTaskId(taskId);
            ListAimSendDetailsResponse listAimSendDetailsResponse = kmClient.listAimSendDetails(
                listAimSendDetailsRequest);
            System.out.println(JsonUtils.toJSON(listAimSendDetailsResponse));
        }
    }

    /**
     * 构建上传智能信息模板素材请求
     *
     * @return UploadAimTemplateMaterialRequest 上传智能信息模板素材请求
     */
    public static UploadAimTemplateMaterialRequest buildUploadAimTemplateMaterialRequest() {
        UploadAimTemplateMaterialRequestBody body = new UploadAimTemplateMaterialRequestBody()
            // 资源类型，可选值：image, video, thumbnail
            .withResourceType("image")
            // 文件类型，可选值：url-资源url链接地址, stream-多媒体资源文件流的BASE64编码，需要带资源类型前缀
            .withFileType("url")
            // 资源文件URL
            .withFileUrl("<YOUR fileUrl>")
            // 素材ID，最大长度36
            .withMaterialId(UUID.randomUUID().toString())
            // 图像比例，可选值：oneToOne, sixteenToNine, threeToOne, fortyEightToSixtyFive, twentyOneToNine
            .withImageRate("sixteenToNine")
            // 素材描述信息
            .withDescription("<YOUR description>");
        UploadAimTemplateMaterialRequest request = new UploadAimTemplateMaterialRequest();
        request.withBody(body);
        return request;
    }

    /**
     * 智能信息上传模板素材
     *
     * @param kmClient KooMessage sdk 客户端
     * @param request  上传模板素材请求
     * @return UploadAimTemplateMaterialResponse 上传模板素材响应
     */
    public static UploadAimTemplateMaterialResponse uploadAimTemplateMaterial(KooMessageClient kmClient,
        UploadAimTemplateMaterialRequest request) {
        UploadAimTemplateMaterialResponse response = new UploadAimTemplateMaterialResponse();
        try {
            response = kmClient.uploadAimTemplateMaterial(request);
            logger.info(response.toString());
            return response;
        } catch (ConnectionException | RequestTimeoutException e) {
            logger.error("uploadAimTemplateMaterial error.", e);
        } catch (ServiceResponseException e) {
            logger.error("httpStatusCode: {}, requestId: {}, errorCode: {}, errorMsg: {}", e.getHttpStatusCode(),
                e.getRequestId(), e.getErrorCode(), e.getErrorMsg());
        }
        return response;
    }

    /**
     * 构建创建智能信息个人模板请求
     *
     * @return CreateAimPersonalTemplateRequest 创建智能信息个人模板请求
     */
    public static CreateAimPersonalTemplateRequest buildCreateAimPersonalTemplateRequest() {
        CreateAimPersonalTemplateRequest request = new CreateAimPersonalTemplateRequest();
        List<AimPersonalTemplatePage> pages = buildAimPersonalTemplatePages();
        List<AimPersonalTemplateFactory> templateFactories = buildAimPersonalTemplateFactories();

        CreateAimPersonalTemplateRequestBody body = new CreateAimPersonalTemplateRequestBody()
            // 模板用途，可选值：1-商用, 2-试商用
            .withUseId(2)
            // 布局类型，可选值：StandardImageAndText-图文类, MultipleImageAndText-多图文类, RedPacket-红包类等
            .withCardId("StandardImageAndText")
            // 模板名称，试商用模板名称要包含"测试"字样
            .withTplName("<YOUR tplName>")
            // 模板协议
            .withPages(pages)
            // 模板参数集
            .withParams(Collections.emptyList()).withFactorys(templateFactories);
        request.withBody(body);
        return request;
    }

    /**
     * 构建智能信息个人模板支持厂商列表
     *
     * @return List<AimPersonalTemplateFactory> 模板支持厂商列表
     */
    private static List<AimPersonalTemplateFactory> buildAimPersonalTemplateFactories() {
        List<AimPersonalTemplateFactory> templateFactories = new ArrayList<>(3);
        AimPersonalTemplateFactory huaweiFactory = new AimPersonalTemplateFactory().withFactoryType("HUAWEI")
            // 支持状态，可选值：1-支持, 0-不支持
            .withState(1);
        templateFactories.add(huaweiFactory);
        AimPersonalTemplateFactory xiaomiFactory = new AimPersonalTemplateFactory().withFactoryType("XIAOMI")
            .withState(1);
        templateFactories.add(xiaomiFactory);
        AimPersonalTemplateFactory oppoFactory = new AimPersonalTemplateFactory().withFactoryType("OPPO").withState(1);
        templateFactories.add(oppoFactory);
        return templateFactories;
    }

    /**
     * 构建智能信息个人模板协议
     *
     * @return List<AimPersonalTemplatePage> 模板协议
     */
    private static List<AimPersonalTemplatePage> buildAimPersonalTemplatePages() {
        List<AimPersonalTemplatePage> pages = new ArrayList<>(1);
        AimPersonalTemplatePage page = new AimPersonalTemplatePage();
        List<AimPersonalTemplateContent> contents = new ArrayList<>(4);
        // 智能信息模板图片组件
        AimPersonalTemplateContent imageContent = new AimPersonalTemplateContent()
            // 模板资源类型，可选值：text-文本, image-图片, video-视频, button-按钮, followPub-华为服务号，暂不支持
            .withType("image")
            // 资源类型，可选值：1-模板素材资源id, 2-资源url地址
            .withSrcType(1)
            // 模板素材上传资源id，即上传素材接口中返回的aim_resource_id
            .withSrc("<YOUR aimResourceId>")
            // 功能类型：可选值：OPEN_URL-跳转H5, OPEN_APP-跳转APP, OPEN_BROWSER-打开浏览器等
            .withActionType("OPEN_BROWSER")
            // 个人模板事件对象
            .withAction(new AimPersonalTemplateContentAction()
                // 此字段根据action_type对应不同的含义，当前表示打开浏览器地址
                .withTarget("<YOUR targetUrl>"))
            // 卡片组件位置序号
            .withPositionNumber(1);
        contents.add(imageContent);
        // 智能信息模板标题组件，试商用标题要包含"测试"字样
        AimPersonalTemplateContent titleContent = new AimPersonalTemplateContent().withType("text")
            .withContent("<YOUR templateTitle>")
            // 是否为文本标题
            .withIsTextTitle("true")
            .withPositionNumber(2);
        contents.add(titleContent);
        // 智能信息模板正文组件，试商用正文要包含"测试"字样
        AimPersonalTemplateContent mainContent = new AimPersonalTemplateContent().withType("text")
            .withContent("<YOUR templateText>")
            .withIsTextTitle("false")
            .withPositionNumber(3);
        contents.add(mainContent);
        // 智能信息模板按钮组件
        AimPersonalTemplateContent buttonContent = new AimPersonalTemplateContent().withType("button")
            .withContent("<YOUR templateButton>")
            .withActionType("OPEN_BROWSER")
            .withPositionNumber(4)
            .withAction(new AimPersonalTemplateContentAction().withTarget("<YOUR targetUrl>"));
        contents.add(buttonContent);
        page.withContents(contents).withPageOrder(1);
        pages.add(page);
        return pages;
    }

    /**
     * 创建智能信息个人模板
     *
     * @param kmClient KooMessage sdk 客户端
     * @param request  创建智能信息个人模板请求
     * @return CreateAimPersonalTemplateResponse 创建智能信息个人模板响应
     */
    public static CreateAimPersonalTemplateResponse createAimPersonalTemplate(KooMessageClient kmClient,
        CreateAimPersonalTemplateRequest request) {
        CreateAimPersonalTemplateResponse response = new CreateAimPersonalTemplateResponse();
        try {
            response = kmClient.createAimPersonalTemplate(request);
            logger.info(response.toString());
            return response;
        } catch (ConnectionException | RequestTimeoutException e) {
            logger.error("createAimPersonalTemplate error.", e);
        } catch (ServiceResponseException e) {
            logger.error("httpStatusCode: {}, requestId: {}, errorCode: {}, errorMsg: {}", e.getHttpStatusCode(),
                e.getRequestId(), e.getErrorCode(), e.getErrorMsg());
        }
        return response;
    }

    /**
     * 根据模板ID查询智能信息模板
     *
     * @param kmClient 请求客户端
     * @param tplId    模板ID
     * @return AIMTemplate 智能信息模板信息
     */
    public static AIMTemplate getAimTemplateById(KooMessageClient kmClient, String tplId) {
        AIMTemplate aimTemplate = new AIMTemplate();
        try {
            ListAimTemplatesRequest request = new ListAimTemplatesRequest();
            request.setTplId(tplId);
            ListAimTemplatesResponse listAIMTemplatesResponse = kmClient.listAimTemplates(request);
            logger.info(listAIMTemplatesResponse.toString());
            List<AIMTemplate> templates = listAIMTemplatesResponse.getTemplates();
            if (templates != null && templates.size() > 0) {
                return templates.get(0);
            }
        } catch (ConnectionException | RequestTimeoutException e) {
            logger.error("getAimTemplateById error.", e);
        } catch (ServiceResponseException e) {
            logger.error("httpStatusCode: {}, requestId: {}, errorCode: {}, errorMsg: {}", e.getHttpStatusCode(),
                e.getRequestId(), e.getErrorCode(), e.getErrorMsg());
        }
        return aimTemplate;
    }

    /**
     * 创建智能信息发送任务
     *
     * @param kmClient 请求客户端
     * @param tplId    模板ID
     * @return CreateAimSendTaskResponse 发送任务响应
     */
    public static CreateAimSendTaskResponse createSendTask(KooMessageClient kmClient, String tplId) {
        CreateAimSendTaskResponse sendTaskResponse = new CreateAimSendTaskResponse();
        try {
            AIMResolveTask resolve = buildAimResolveTask(tplId);
            SmsChannel smsChannel = buildSmsChannel();
            CreateAimSendTaskRequestBody body = new CreateAimSendTaskRequestBody()
                // 智能信息发送任务名称
                .withTaskName("<YOUR taskName>")
                // 短息发送通道参数
                .withSmsChannel(smsChannel)
                // 短链生成配置
                .withResolveTask(resolve);
            CreateAimSendTaskRequest request = new CreateAimSendTaskRequest();
            request.setBody(body);
            sendTaskResponse = kmClient.createAimSendTask(request);
            System.out.println(sendTaskResponse);
            return sendTaskResponse;
        } catch (ConnectionException | RequestTimeoutException e) {
            logger.error("createSendTask error.", e);
        } catch (ServiceResponseException e) {
            logger.error("httpStatusCode: {}, requestId: {}, errorCode: {}, errorMsg: {}", e.getHttpStatusCode(),
                e.getRequestId(), e.getErrorCode(), e.getErrorMsg());
        }
        return sendTaskResponse;
    }

    /**
     * 构建短链生成配置
     *
     * @param tplId 智能信息模板ID
     * @return AIMResolveTask 短链生成配置
     */
    private static AIMResolveTask buildAimResolveTask(String tplId) {
        // 您可以设置自己要发送的目标手机号，如果发送多个请按需创建多个param加入params数组中
        String targetPhone = "<YOUR targetPhone>";
        CreateResolveTaskParam param = new CreateResolveTaskParam()
            // 解析任务用户唯一标识，发送时必填用户手机号码
            .withCustFlag(targetPhone);
        List<CreateResolveTaskParam> params = new ArrayList<>();
        AIMResolveTask resolve = new AIMResolveTask()
            // 模板ID
            .withTplId(tplId)
            // 编码类型，可选值：group-群发，individual-个性化
            .withAimCodeType("individual")
            // 短链最大解析次数
            .withResolveTimes(1)
            // 短链解析详情列表
            .withParams(params)
            // 短链失效时间（天）
            .withExpirationTime(7);
        params.add(param);
        return resolve;
    }

    /**
     * 构建短信发送通道参数
     *
     * @return SmsChannel 短息发送通道参数
     */
    private static SmsChannel buildSmsChannel() {
        return new SmsChannel()
            // 短信模板签名所绑定的通道号，KooMessage控制台-》短消息签名管理-》通道号
            .withChannelNumber("<YOUR smsChannelNumber>")
            // 短信模板所属签名，KooMessage控制台-》短消息模板管理-》所属签名
            .withSmsSign("<YOUR smsSign>")
            // 短信模板ID，KooMessage控制台-》短消息配置（国内）-》短消息模板管理-》模板ID
            .withSmsTplId("<YOUR smsTplId>")
            // 短信应用名称，KooMessage控制台-》短消息配置（国内）-》短消息模板管理-》所属应用
            .withSmsAppName("<YOUR smsAppName>");
    }
}
